const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const app = express();
const cors = require('cors')

// app.use(cors)

// 后端配置跨域
app.all('*', function(req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header('Access-Control-Allow-Headers', 'Content-type');
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
    //可选，用来指定本次预检请求的有效期，单位为秒。在此期间，不用发出另一条预检请求。
    res.header('Access-Control-Max-Age', 1728000); //预请求缓存20天
    next();
});

// 用户
const users = require("./routes/api/users")
    // 考勤
const attendance = require("./routes/api/attendance")
    // 班级
const className = require("./routes/api/className")
    // 课程
const curriculum = require("./routes/api/curriculum")
    // 学院
const college = require("./routes/api/college")
    // 请假
const leave = require("./routes/api/leave")

// 使用bodyParser中间件
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 连接数据库
const db = require("./config/keys").mongoURL;
mongoose.connect(db, { useNewUrlParser: true }).then(res => {
    console.log("数据库连接成功");
}).catch(err => console.log(err));

// passport 初始化
app.use(passport.initialize());

require('./config/passport')(passport);

app.get("/", (req, res) => {
    res.send("test");
});

// 使用routes
app.use("/api/users", users);
app.use("/api/attendance", attendance)
app.use("/api/className", className)
app.use("/api/curriculum", curriculum)
app.use("/api/college", college)
app.use("/api/leave", leave)

mongoose.set('useFindAndModify', false);

const port = process.env.PORT || 3000;

app.listen(port, () => {
    console.log("服务器启动成功,端口号" + port);
});